
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "tiffio.h"


int main(int argc, char** argv) {

      TIFF* outtif = TIFFOpen("output.tif", "w"); 
    	
	
	
	
   uint32  width,height; 
	TIFF* tif = TIFFOpen("binesh.tif", "r"); 
	if (tif) {
	         
	            char emsg[1024];

			     TIFFGetField(tif, TIFFTAG_IMAGEWIDTH,  &width);
                 TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height );
			     
				 
			 TIFFSetField(outtif, TIFFTAG_IMAGEWIDTH,width);
		         TIFFSetField(outtif, TIFFTAG_IMAGELENGTH, height );
			 TIFFSetField(outtif, TIFFTAG_BITSPERSAMPLE, 8);
			 TIFFSetField(outtif, TIFFTAG_COMPRESSION,  COMPRESSION_PACKBITS);
		         TIFFSetField(outtif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
		         TIFFSetField(outtif, TIFFTAG_SAMPLESPERPIXEL, 3);
		         TIFFSetField(outtif, TIFFTAG_ROWSPERSTRIP, 1);
		         TIFFSetField(outtif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
		         TIFFSetField(outtif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_NONE);
		         TIFFSetField(outtif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
	
	
			  
			  
			  
			  
	              size_t npixels;
	              uint32* raster; 
				  int                 i = 0,j=0;   
	              npixels =width * height; 
	              raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32));
			     // uint8 image[width][TIFFScanlineSize(outtif)];
				  uint8              *buf;
				  buf = (uint8 *) _TIFFmalloc(TIFFScanlineSize(tif));
				  int col,row,offset;
				  
				  if (raster != NULL) {
	               
			             TIFFReadRGBAImageOriented(tif,width,height,raster,ORIENTATION_TOPRIGHT,0);
							
							 for ( row= 0; row < height; row++)
						   {
							
								 i = 0;
								 j=0;
								 for ( col= 0; col < width; col++)
								{
									
											buf[i++]= TIFFGetR(raster[row*width+col]);
											buf[i++]= TIFFGetG(raster[row*width+col]);
											buf[i++]= TIFFGetB(raster[row*width+col]);
									 
									}
									TIFFWriteScanline(outtif, buf, row, 0);			
								}
			  //for ( row= 0; row < width; row++)
						 //  {
							  
						//	TIFFWriteScanline(outtif,&image[row], row, 0);
						  //  }
			
			                        
					
					}
					
					
					
					 _TIFFfree(raster);
					
	 
	
	
	
	}
	TIFFClose(outtif);
	
	TIFFClose(tif);

    return (EXIT_SUCCESS);
}
